<!--密钥管理-->
<template>
  <div id="proof" class="app-container">
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord">
          <template slot="rightTool">
            <search v-model="listQuery.projectName" placeholder="请输入密钥名称" @search="handleFilter" />
            <export-drop-down class-name="proof" :list-query="listQuery" title="密钥" />
          </template>
        </table-toolbar>
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="项目名称" prop="projectName" sortable min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <i v-if="scope.row.isSelf===1" class="el-icon-lock color-danger" />
            {{ scope.row.projectName }}
          </template>
        </el-table-column>
        <el-table-column label="AppId" prop="appId" width="170">
          <template slot-scope="scope">
            <copy-text :content="scope.row.appId" position="left" />
          </template>
        </el-table-column>
        <el-table-column label="AppKey" prop="appKey" width="260">
          <template slot-scope="scope">
            <copy-text :content="scope.row.appKey" position="left" />
          </template>
        </el-table-column>
        <el-table-column label="签名Key" prop="signKey" width="120">
          <template slot-scope="scope">
            <copy-text :content="scope.row.signKey" position="left" />
          </template>
        </el-table-column>
        <el-table-column label="公钥" prop="publicKey" :show-overflow-tooltip="true" min-width="60">
          <template slot-scope="scope">
            <copy-text :content="scope.row.publicKey" :show="false" />
          </template>
        </el-table-column>
        <el-table-column label="私钥" prop="privateKey" :show-overflow-tooltip="true" min-width="60">
          <template slot-scope="scope">
            <copy-text :content="scope.row.privateKey" :show="false" />
          </template>
        </el-table-column>
        <el-table-column label="是否启用" prop="isDisabled" width="80" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isDisabled"
              @change="changeIsState(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="项目描述" prop="projectDesc" min-width="200" align="left" show-overflow-tooltip />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="proofRules"
          :model="proofRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="项目名称:" prop="projectName">
            <el-input v-model="proofRecord.projectName" maxlength="20" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item v-if="sideBox.status==='update'" label="AppId:" prop="appId">
            <el-input v-model="proofRecord.appId" disabled="disabled" />
          </el-form-item>
          <el-form-item v-if="sideBox.status==='update'" label="AppKey:" prop="appKey">
            <el-input v-model="proofRecord.appKey" disabled="disabled" />
          </el-form-item>

          <el-form-item v-if="sideBox.status==='update'" label="AppSecret:" prop="appSecret">
            <el-input v-model="proofRecord.appSecret" disabled="disabled" />
          </el-form-item>

          <el-form-item v-if="sideBox.status==='update'" label="密钥签名:" prop="signKey">
            <el-input v-model="proofRecord.signKey" disabled="disabled" />
          </el-form-item>

          <el-form-item label="应用渠道:" prop="isSelf">
            <el-radio v-model="proofRecord.isSelf" :disabled="sideBox.status==='update'" label="0">三方</el-radio>
            <el-radio v-model="proofRecord.isSelf" :disabled="sideBox.status==='update'" label="1">自营</el-radio>
            <div class="common-explain color-warning">说明：选择选项'是'，此记录不可删除，可编辑，选择选项'否'，此记录可删除，可编辑</div>

          </el-form-item>
          <el-form-item label="项目描述:" prop="projectDesc">
            <el-input
              v-model="proofRecord.projectDesc"
              :rows="4"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        projectName: undefined,
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },
      proofRecord: {
        isSelf: '0'
      },
      proofRules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }

        ],
        isSelf: [
          { required: true, message: '请选择应用渠道', trigger: 'blur' }
        ],
        projectDesc: [
          { required: true, message: '请输入项目描述', trigger: 'blur' }

        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 表格自带方法开始
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /**
     * 表格行数据单击
     */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /**
     * 表格列排序
     */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    async fetchData() {
      const response = await this.$store.dispatch('proofPage', this.listQuery)
      this.list = response.records
      this.list.filter((item) => {
        item.isDisabled = !item.isDisabled
        return true
      })
      this.total = response.total
    },

    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        projectName: undefined,
        sort: this.common.SORT_DEFAULT
      }

      this.fetchData()
    },

    /* 新增*/
    handleCreate() {
      this.proofRecord = {
        isSelf: '0'
      }
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '新增密钥'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('proofSave', this.proofRecord).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 编辑*/
    handleUpdate(row) {
      this.proofRecord = Object.assign({}, row) // copy obj
      this.proofRecord = {
        ...this.proofRecord,
        isSelf: this.proofRecord.isSelf + ''
      }
      this.sideBox = {
        status: 'update',
        recordShow: true,
        title: `编辑密钥[${this.proofRecord.projectName}]`
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      this.proofRecord.isDisabled = null
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.proofRecord)
          this.$store.dispatch('proofUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          if (v.isSelf === 0) {
            ids.push(v.id)
          }
        })
        if (ids.length === 0) {
          this.msgWarning('你选择的数据都是内置数据,无权删除')
          return
        }
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('proofRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },

    changeIsState(row) {
      if (row.isSelf === 1) {
        this.msgWarning('你选择的数据都是内置数据,无权操作')
        row.isDisabled = !row.isDisabled
        return
      }
      var temp = Object.assign({}, row) // copy obj

      this.$confirm('您确定' + (temp.isDisabled === false ? '禁用' : '启用') + '项目[' + temp.projectName + '], 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          const params = {
            id: temp.id,
            isDisabled: !temp.isDisabled
          }
          this.$store.dispatch('proofChangeIsState', params).then(response => {
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            row.isDisabled = !row.isDisabled
          })
        }).catch(() => {
          row.isDisabled = !row.isDisabled
        })
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
